package cn.yh.hospitalappointmentsystemdemo.controller;

import cn.yh.hospitalappointmentsystemdemo.common.AjaxResult;
import cn.yh.hospitalappointmentsystemdemo.controller.base.BaseController;
import cn.yh.hospitalappointmentsystemdemo.domain.entity.User;
import cn.yh.hospitalappointmentsystemdemo.service.IUserService;
import cn.yh.hospitalappointmentsystemdemo.utils.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;


    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public AjaxResult userLogin(@RequestBody User user){
        if (user == null || user.getUsername() == null || user.getRole() == null) {
            return AjaxResult.error("用户信息不完整");
        }
        Map<String, Object> result = new HashMap<>();
        System.out.println("User"+user);

        User userDb = userService.checkLogin(user);

        if (userDb == null){
            return AjaxResult.error("账号或密码错误");
        }
        if (!user.getPassword().equals(userDb.getPassword())){
            return AjaxResult.error("错误的密码");
        }
//        System.out.println("UID"+userDb.getUId()+"  role: "+user.getRole());
        Object userVo = userService.getUserVo(userDb.getUId(), user.getRole());
        if (userVo == null){
            return AjaxResult.error("用户不存在");
        }
        System.out.println("userDb: "+userDb);
        String token = JWTUtils.createToken(userDb);
        result.put("user", userVo);
        result.put("token", token);
        return AjaxResult.success(result);
    }
}
